var nextPermutation = function (nums) {
  let pos = nums.length - 1
  let range_max = 0
  const bubble = (nums, pos) => {
    for (let i = 0; i < nums.length - pos; i++) {
      for (let j = pos; j < nums.length - i; j++) {
        let temp
        if (nums[j] > nums[j + 1]) {
          temp = nums[j]
          nums[j] = nums[j + 1]
          nums[j + 1] = temp
        }
      }
    }
  }
  while (pos > 0) {
    if (nums[pos] > range_max)
      range_max = nums[pos]
    if (range_max > nums[pos - 1]) {
      bubble(nums, pos)
      for (let i = pos; i < nums.length; i++) {
        if (nums[pos - 1] < nums[i]) {
          let temp
          temp = nums[pos - 1]
          nums[pos - 1] = nums[i]
          nums[i] = temp
          break
        }
      }
      break
    }
    pos--
  }
  if (pos == 0) {
    bubble(nums, 0)
  }
  console.log(nums)
  return nums
}
/**
 * 从后往前：当前指针为pos，如果[pos, nums.length - 1]
 * 存在一个数比nums[pos-1]大，则找出使这个条件成立的最小的数
 * 与nums[pos - 1]交换。
 * 返回就行
 */
function bubble (nums, pos) {
  for (let i = 0; i < nums.length - pos; i++) {
    for (let j = pos; j < nums.length - i; j++) {
      let temp
      if (nums[j] > nums[j + 1]) {
        temp = nums[j]
        nums[j] = nums[j + 1]
        nums[j + 1] = temp
      }
    }
  }
}
// nextPermutation([1, 2, 3])
nextPermutation([1, 1, 2, 5, 1])
// nextPermutation([3, 2, 1])
// nextPermutation([1, 1, 5])